package com.ysf.cn.mainshi.test;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author ysf
 * @date 2020/2/24 15:49
 */
public class MyTestThread {
    /**
     * 使用队列Condition唤醒部分线程,使用ReentrantLock进行加锁,来保证线程能顺序执行
     */
    static class MyTask{
        private static ReentrantLock r1=new ReentrantLock();
        private static Condition conditionA=r1.newCondition();
        private static Condition conditionB=r1.newCondition();
        private static Condition conditionC=r1.newCondition();

        public void execute(String flag){
            r1.lock();
            try {
                for (int i = 1; i <=10 ; i++) {
                     if("A".equals(flag)){
                         System.out.println(Thread.currentThread().getName()+"-"+i);
                         //conditionA.signal();
                         //conditionA.await();
                     }
                    if("B".equals(flag)){
                        System.out.println(Thread.currentThread().getName()+"-"+i);
//                        conditionB.signal();
//                        conditionB.await();
                    }
                    if("C".equals(flag)){
                        System.out.println(Thread.currentThread().getName()+"-"+i);
//                        conditionC.signal();
//                        conditionC.await();
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                r1.unlock();
            }
        }
    }

    public static void main(String[] args) {
        final MyTask myTask=new MyTask();
        new Thread(new Runnable() {
            @Override
            public void run() {
                myTask.execute("A");
            }
        },"A").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                myTask.execute("B");
            }
        },"B").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                myTask.execute("C");
            }
        },"C").start();
    }
}
